from crewai.tools import tool
from ddgs import DDGS


@tool("ddgs_text_search文本搜索")
def ddgs_text_search(query: str, max_results: int = 5) -> str:
    """
       使用DuckDuckGo搜索引擎进行文本搜索
       Args:
           query (str): 搜索关键词
       Returns:
           str: 搜索结果
       """
    ddgs = DDGS()
    try:
        results = ddgs.text(
            query=query,
            max_results=max_results,
            backend="auto", # 使用自动选择后端,
            region='zh-cn'
        )
        output = []
        for i, result in enumerate(results, 1):
            output.append(f"\n结果 {i}:")
            output.append(f"标题: {result.get('title', 'N/A')}")
            output.append(f"链接: {result.get('href', 'N/A')}")
            output.append(f"摘要: {result.get('body', 'N/A')[:200]}...")
            output.append("-" * 50)
        return "\n".join(output)
    except Exception as e:
        return f"搜索失败: {str(e)}"
